<?php
	require_once ("../../includes/config.php");

	$sql = 'SELECT *
    FROM clients
    LEFT JOIN (

    SELECT client_id, MAX( updated_at ) MaxDate
    FROM contracts
    GROUP BY client_id
    )MaxDates ON clients.id = MaxDates.client_id
    LEFT JOIN contracts c ON MaxDates.client_id = c.client_id
    AND MaxDates.MaxDate = c.updated_at
    WHERE clients.owner_id =?';

	$binds = array();

	$binds['owner_id'] = $_SESSION['user_id'];

	if (isset($_GET['name']) || isset($_GET['chosen_client']) || isset($_GET['mobile']))
	{
		if (!empty($_GET['chosen_client']) && $_GET['chosen_client'] != 1)
		{
			if (!empty($binds))
				$and = " and ";
			else
				$and = " ";

			$currentdate = date('Y/m/d', time());

			$binds['chosen_client'] = $currentdate;
			if ($_GET['chosen_client'] == 2)
			{
				$sql .= $and . "miladi_out = ?";
			}
			
else
			if ($_GET['chosen_client'] == 3)
			{
				$binds['status'] = 2;
				$sql .= $and . "miladi_out = ? and contract_status = ?";
			}
			
else
			if ($_GET['chosen_client'] == 4)
			{
				$binds['status'] = 3;
				$sql .= $and . "miladi_out = ? and contract_status = ?";
			}
		}
		if (!empty($_GET['name']))
		{
			if (!empty($binds))
				$and = " and ";
			else
				$and = " ";

			$binds['name'] = $_GET['name'];
			$sql .= $and . "name  = ?";
		}

		if (!empty($_GET['mobile']))//Search by mobile
		{
			//Make sure that binds wasn't already filled
			if (!empty($binds))
				$and = " and ";
			else
				$and = " ";
			
			//Add mobile to binds
			$binds['mobile'] = '%'.$_GET['mobile'].'%';
			$sql .= $and . "mobile LIKE ?";
		}
		//Execute mysql query
		$clients = query($sql, $binds);
		if (empty($clients))
			echo 0;
		else
		{
			$clients = json_encode($clients);
			echo $clients;
		}
	}
	else
	{
		$clients = array();
		renderWithoutHeader("Customers/choose_clients_sms.php", array(
			"clients" => $clients,
			"sentAlert" => "برجاء اختيار احد الفلاتر"
		));
	}
?>